<?php

namespace App\Model\Admin;

use App\Model\BaseModel;
use EasySwoole\Component\Context\ContextManager;
use EasySwoole\Http\Request;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\DbManager;

/**
 * 系统操作日志-模型
 * @author LZH
 * @since: 2021/08/12
 * Class ActionLogModel

 */
class ActionLogModel extends BaseModel
{
    protected $tableName = DB_PREFIX . "action_log";
    // 自定义日志标题
    protected static $title = '';
    // 自定义日志内容
    protected static $content = '';

    public function __construct(array $data = [])
    {
        parent::__construct($data);
        // 设置表名
        $this->tableName = DB_PREFIX . 'action_log_' . date('Y') . '_' . date('m');
        // 初始化行为日志表
        $this->initTable();
    }

    /**
     * 获取缓存信息
     * @param int $id 记录ID
     * @author LZH
     * @since: 2021/08/12
     */
    public function getInfoById($id, $append = [], $visible=[], $hidden = [])
    {
        $info = parent::getInfoById($id);
        if ($info) {
        }
        return $info;
    }

    /**
     * 初始化日志表
     * @return string|null
     */
    private function initTable()
    {
        $tbl = $this->tableName;
        if (!$this->tableExists($tbl)) {
            $sql = "CREATE TABLE `{$tbl}` (
                  `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '唯一性标识',
                  `school_code` varchar(100) NOT NULL COMMENT '学校唯一编码',
                  `username` varchar(60) CHARACTER SET utf8mb4 NOT NULL COMMENT '操作人用户名',
                  `method` varchar(20) CHARACTER SET utf8mb4 NOT NULL COMMENT '请求类型',
                  `module` varchar(30) NOT NULL COMMENT '模型',
                  `action` varchar(255) NOT NULL COMMENT '操作方法',
                  `url` varchar(200) CHARACTER SET utf8mb4 NOT NULL COMMENT '操作页面',
                  `param` text CHARACTER SET utf8mb4 NOT NULL COMMENT '请求参数(JSON格式)',
                  `title` varchar(100) NOT NULL COMMENT '日志标题',
                  `type` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '操作类型：1登录系统 2注销系统 3操作日志',
                  `content` varchar(1000) NOT NULL DEFAULT '' COMMENT '内容',
                  `ip` varchar(18) CHARACTER SET utf8mb4 NOT NULL COMMENT 'IP地址',
                  `user_agent` varchar(360) CHARACTER SET utf8mb4 NOT NULL COMMENT 'User-Agent',
                  `create_user` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '添加人',
                  `create_time` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '添加时间',
                  `mark` tinyint(1) unsigned NOT NULL DEFAULT '1' COMMENT '有效标识：1正常 0删除',
                  PRIMARY KEY (`id`) USING BTREE
                ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COMMENT='系统行为日志表';";

            $queryBuild = new QueryBuilder();
            $queryBuild->raw($sql);
            DbManager::getInstance()->query($queryBuild, true);
        }
        return $tbl;
    }

    /**
     * 设置标题
     * @param string $title 标题
     */
    public static function setTitle($title)
    {
        self::$title = $title;
    }

    /**
     * 设置内容
     * @param string $content 内容
     */
    public static function setContent($content)
    {
        self::$content = $content;
    }

    /**
     * 创建日志
     */
    public static function record()
    {
        $admin = ContextManager::getInstance()->get('user');
        if (!self::$title) {
            // 操作控制器名
            $menuModel = new MenuModel();
            // TODO 获取请求参数
            $url = '';
            $info = $menuModel->getOne([
                ['path' => [$url]],
            ]);
            if ($info) {
                if ($info['type'] == 1) {
                    $menuInfo = $menuModel->getInfoById($info['pid']);
                    self::$title = $menuInfo['title'];
                } else {
                    self::$title = $info['title'];
                }
            }
        }

        /* @var Request $request */
        $request = ContextManager::getInstance()->get('request');
        // 日志数据
        $data = [
            'username' => '管理员',
            'module' => '', // TODO 模块名称
            'action' => '', // TODO 动作名称
            'method' => '', // TODO 方法名称,
            'url' => $request->getUri(), // 获取完整的URL
            'param' =>  $request->getRequestParam() ? json_encode($request->getRequestParam()) : '',
            'title' => self::$title ?: '操作日志',
            'type' => self::$title == '登录系统' ? 1 : (self::$title == '注销系统' ? 2 : 3),
            'content' => self::$content,
            'ip' => '',
            'user_agent' => '',
            'create_user' => $admin['id'] ?? 0 ,
            'create_time' => time(),
        ];
        // 日志入库
        self::saveAll($data);
    }
}
